import produce from "immer"

const initState = {
  token: localStorage.getItem("token") || null,
  avatar: "",
  introduction: "",
  name: "",
  roles: [],
  accessRoutes: []
}

// 导出一个reducer，有两个参数
// 一个是state，一个是action
// state是老状态，state = initState,action) 给状态提供初始值
// 一个action是一个对象，一个type，表示信号，一个payload，表示负荷
export default (state = initState, { type, payload }) => {
  // 1）对老状态进行深copy（数据不变可）
  // 2）根据action中的type和payload对状态进行CRUD
  // 3）返回新状态

  return produce(state, newState => {
    // 根据action中的type和payload对状态进行CRUD
    switch (type) {
      case "USER_LOGIN":
        newState.token = payload;
        localStorage.setItem("token", payload)
        break;
      case "USER_INFO":
        const { avatar, introduction, name, roles } = payload;
        newState.avatar = avatar;
        newState.introduction = introduction;
        newState.name = name;
        newState.roles = roles;
        break;
      case "USER_RESET":
        localStorage.removeItem("token")
        newState.avatar = "";
        newState.introduction = "";
        newState.name = "";
        newState.roles = [];
        newState.token = "";
        break;
      case "USER_PERMISSION":
        newState.accessRoutes = payload;
      default:
        break;
    }
  })
}
